<template>
  <el-form ref="postForm" :model="postForm" :rules="rules">
    <sticky :class-name="'sub-navbar'">
      <el-button v-if="!isEdit" @click="showGuide">显示帮助</el-button>
      <el-button
        v-loading="loading"
        type="success"
        style="margin-left: 10px"
        @click="submitForm"
      >
        {{ isEdit ? '编辑新闻' : '新增新闻' }}
      </el-button>
    </sticky>
    <div class="detail-container">
      <el-row>
        <warning />
        <el-col :span="24">
          <el-row>
            <el-col :span="24">
              <el-form-item prop="title" label="标题：" :label-width="labelWidth" >
                <el-input
                  v-model="postForm.title"
                  placeholder="标题"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="columnid" label="类型：" :label-width="labelWidth">
                <el-select v-model="postForm.columnid" placeholder="请选择" clearable>
                 <el-option
                   v-for="item in categoryList"
                   :key="item.value"
                   :label="item.label + '(' + item.num + ')'"
                   :value="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="attribute" label="推荐：" :label-width="labelWidth">
                <el-checkbox v-model="postForm.attribute">推荐</el-checkbox>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item prop="abstract" label="简介：" :label-width="labelWidth">
                <el-input
                  v-model="postForm.abstract"
                  placeholder="简介"
                  type="textarea"
                  :row="4"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="photo" label="上传新闻封面：" :label-width="labelWidth">
                <el-upload
                  class="upload-demo"
                  ref="upload"
                  action="https://test.resume1234.top:18082/news/uploadNews"
                  name="file"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :data="userInfo"
                  :file-list="fileList"
                  list-type="picture"
                  :auto-upload="false"
                  :on-success="onsuccess"
                  :before-upload="beforeAvatarUpload"
                  multiple
                >
                  <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
                  <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg图片，且不超过2MB</div>
                </el-upload>
              </el-form-item>
                </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item prop="body" label="内容：" :label-width="labelWidth">
                <markdown-editor v-model="postForm.body" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item prop="visit" label="访问量：" :label-width="labelWidth">
                <el-input
                  v-model="postForm.visit"
                  placeholder="访问量"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="state" label="显示：" :label-width="labelWidth">
                <el-radio v-model="postForm.state" label="1">显示</el-radio>
                <el-radio v-model="postForm.state" label="2">隐藏</el-radio>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </div>
  </el-form>
</template>

<script>
// eslint-disable-next-line
/* eslint-disable */
import Cookies from 'js-cookie'
import Sticky from '../../../components/Sticky'
import Warning from './Warning'
import { createNews, getCategory, updateNews, getOneNews } from '../../../api/news'
import MarkdownEditor from '@/components/MarkdownEditor'
const fields = {
  title: '书名',
  author: '作者',
  publisher: '出版社',
  language: '语言'
}
export default {
  components: { Sticky, Warning, MarkdownEditor },
  props: {
    isEdit: Boolean
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error(fields[rule.field] + '必须填写'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      postForm: {},
      fileList: [],
      fileList_enroll:[],
      labelWidth: '120px',
      categoryList:[],
      userInfo: {},
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        columnid: [{required: true, message: '请选择类别', trigger: 'change'}],
        abstract: [{ required: true, message: '请输入简介', trigger: 'blur' }],
        body: [{ required: true, message: '请输入内容', trigger: 'blur' }],
        photo: [{ required: true, message: '请上传图片', trigger: 'blur' }]
      }
    }
  },
  created() {
    //获取用户信息
    let usernameinfo=Cookies.get('username')
    //console.log(usernameinfo)
    this.userInfo={"username":usernameinfo}
    if (this.isEdit) {
      const fileName = this.$route.params.fileName
      getOneNews(fileName).then(response => {
        console.log(response)
        this.postForm=response.data
        this.arr1 = JSON.parse(response.data.photo)
        console.log(this.arr1)
        this.arr1.forEach((item)=>{
          console.log(item.name)
            this.fileList.push({name: item.name, url: item.url})
            console.log(this.fileList)
        })
      }
   ).catch(() => {
        this.loading = false
      })
      console.log(fileName)
    }
    this.getCategoryList()
  },
  methods: {
    onContentClick(data) {
      console.log(data)
      if (data.text) {
        window.open(data.text)
      }
    },
    setDefault() {
      // this.postForm = Object.assign({}, defaultForm)
      this.fileList = []
      //this.postForm={state:"1"}
    },
    onsuccess(res){
      this.$notify({
          title: '上传图片成功',
          message: '上传图片成功',
          type: 'success',
          duration: 2000
        })
      console.log(res)
      this.fileList_enroll.push({name:res.data, url:res.data})
      //this.fileList.push()
      this.postForm.enroll_img=this.fileList_enroll
      //this.fileList.push({name: res.data, url:res.data})
      this.postForm.photo=this.fileList
      
    },
    submitUpload(){
        this.$refs.upload.submit();
    },
    handlePreview(file){

    },
    beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
    },

    handleRemove(file, fileList) {
      this.setDefault()
    },
    getCategoryList() {
      getCategory().then(response => {
        this.categoryList = response.data
        console.log(response)
      })
      console.log(this.categoryList)
    },
    submitForm() {
      const onSuccess = (response) => {
        const { msg } = response
        this.$notify({
          title: '操作成功',
          message: msg,
          type: 'success',
          duration: 2000
        })
        this.loading = false
      }

      if (!this.loading) {
        this.loading = true
        this.$refs.postForm.validate((valid, fields) => {
          console.log(valid, fields)
          if (valid) {
            const news = Object.assign({}, this.postForm)
            console.log(news)
            if (!this.isEdit) {
              createNews(news).then(response => {
                onSuccess(response)
                this.setDefault()
              }).catch(() => {
                this.loading = false
              })
            } else {
              updateNews(news).then(response => {
                onSuccess(response)
              }).catch(() => {
                this.loading = false
              })
            }
          } else {
            const message = fields[Object.keys(fields)[0]][0].message
            this.$message({ message, type: 'error' })
            this.loading = false
          }
        })
      }
    },
    showGuide() {
      console.log('show guide...')
    }
  }
}
</script>

<style lang="scss" scoped>
  .detail-container {
    padding: 40px 50px 20px;
    .preview-img {
      width: 200px;
      height: 270px;
    }
  }
</style>
